<template>
  <div class="music-list">
    <div class="header">
      <div v-show="songSheet.img" :style="{backgroundImage: `url(${songSheet.img})`}" ref="musicImg"></div>
      <div>
        <span :title="songSheet.title">{{ songSheet.title }}</span>
        <span :title="songSheet.user">{{ songSheet.user }}</span>
        <!--        <span></span>-->
        <span class="tool">
          <div @click="playMusicAll">
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#icon-bofangqi-bofang"></use>
            </svg>
            <span v-show="!operation">播放全部</span>
            <span v-show="operation">播放选中</span>
          </div>
          <div v-show="operation && additionShow">
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#icon-tianjia"></use>
            </svg>
            <span>添加到播放列表</span>
          </div>
          <div v-show="operation && downloadShow">
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#icon-xiazai"></use>
            </svg>
            <span>下载选中</span>
          </div>
          <div v-show="operation && deleteShow">
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#icon-delete_line"></use>
            </svg>
            <span>删除选中</span>
          </div>
          <div @click="batchOperation">
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#icon-guanlishipin"></use>
            </svg>
            <span v-show="!operation">批量操作</span>
            <span v-show="operation">退出批量操作</span>
          </div>
        </span>
      </div>
    </div>
    <div class="table">
      <table>
        <thead>
        <tr>
          <td><input type="checkbox" v-show="operation" v-model="checkAll"/></td>
          <td>歌曲</td>
          <td>歌手</td>
          <td>专辑</td>
          <td>大小</td>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(m,index) in musicInfoList" :key="m.id"
            :class="getClass(m.isPlay,m.isPlaying)">
          <td>
            <div>
              <input type="checkbox" v-show="operation" v-model="m.isSelected"/>
            </div>
          </td>
          <td>
            <div>
              <span class="not-active">
                {{ m.title }}&nbsp;&nbsp;
              </span>
              <span class="not-active" v-show="m.isPlaying">
                <svg class="icon" aria-hidden="true">
                <use xlink:href="#icon-shengyin"></use>
              </svg>
              </span>
            </div>
            <div>
              <span class="not-active" @click="play(index)">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-bofangqi-bofang" v-show="!m.isPlaying"></use>
                  <use xlink:href="#icon-bofangqi-zanting" fill="#E6EAEF" v-show="m.isPlaying"></use>
                </svg>
              </span>
              <span class="not-active" v-show="!m.isCollection" @click="addCollection(index,true)">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-zhuifanshu"></use>
                </svg>
              </span>
              <span class="active" v-show="m.isCollection" @click="addCollection(index,false)">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-yizhuifan"></use>
                </svg>
              </span>
              <span class="not-active">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-xiazai"></use>
                </svg>
              </span>
              <span class="not-active">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-danlieliebiao"></use>
                </svg>
              </span>
            </div>
          </td>
          <td>{{ m.artist }}</td>
          <td>{{ m.album }}</td>
          <td>{{ m.size }}</td>
        </tr>
        </tbody>
        <tfoot></tfoot>
      </table>
    </div>
  </div>
</template>

<script>
import {useStore} from "vuex";
import {useRoute} from "vue-router";
import {onBeforeUnmount, onMounted, reactive, getCurrentInstance, computed, ref} from "vue";
import {addMark} from "@/music";
// 获取当前组件实例

export default {
  name: "MusicList",
  setup(props, context) {
    const store = useStore();
    const route = useRoute();
    const backgroundImage = "./resources/static/local.jpg";
    const music = getCurrentInstance().appContext.config.globalProperties.$music;
    const modal = getCurrentInstance().appContext.config.globalProperties.$modal;
    const alert = getCurrentInstance().appContext.config.globalProperties.$alert;

    // 添加到播放列表按钮是否显示
    let additionShow = ref(false);

    // 下载选中按钮是否显示
    let downloadShow = ref(false);

    // 删除选中按钮是否显示
    let deleteShow = ref(false);

    // 批量操作按钮
    let operation = ref(false);

    // 图片与标题及其他信息
    let songSheet = reactive({
      title: "",
      user: "",
      img: "",
      type: ""
    });

    // 歌曲信息
    let musicInfoList;
    //let musicInfoList = store.state.kugouNet.musicList;
    songSheet.type = route.query.type;

    /**
     * 标题：初始化数据，布局页面
     *
     * 变量：type，当前模板<br />
     */
    switch (route.query.type) {
      case "net":
      case "singer":
        store.commit("kugouNet/EMPTY");
        musicInfoList = store.state.kugouNet.musicList;

        if ("net" === route.query.type) {
          store.dispatch("kugouNet/getSongListNetStore", route.query.id);
        } else {
          store.dispatch("kugouNet/getSingerMusicListNetStore", route.query.id);
        }

        songSheet.title = route.query.title;
        songSheet.img = route.query.img;
        songSheet.user = route.query.user;
        downloadShow.value = true;
        additionShow.value = true;
        break;
      case "history":

        musicInfoList = store.getters["history/getMusicList"];
        console.log("history", musicInfoList.length)

        songSheet.title = "历史记录"
        songSheet.img = backgroundImage;
        downloadShow.value = true;
        deleteShow.value = true;
        break;
      case "collection":
        musicInfoList = store.getters["collection/getMusicList"];

        songSheet.title = "我的收藏"
        songSheet.img = backgroundImage;
        downloadShow.value = true;
        deleteShow.value = true;
        break;
      case "local":
        musicInfoList = store.state.local.musicList;
        store.commit("local/EMPTY");
        store.dispatch("local/getMusicListLocalStore", "download");

        songSheet.title = "本地歌曲"
        songSheet.img = backgroundImage;
        deleteShow.value = true;
        break;
      default:
        musicInfoList = store.state.musicList;
        break;
    }


    /**
     * 标题：播放单曲
     *
     * 清空播放列表
     *
     * 变量：<br />
     */
    function play(index) {
      switch (songSheet.type) {
        case "net":
        case "singer": {
          modal.onModal();
          store.state.kugouNet.song = {};
          store.dispatch("kugouNet/getSongNetStore", musicInfoList[index].id);
          let song;
          let interval = setInterval(() => {
            song = store.state.kugouNet.song;
            if (song && (song.url || song.error)) {
              if (song.url) {
                playMusic(song, {});
              } else {
                store.state.kugouNet.musicList[index].isPlay = false;
                alert.dangerAlert("播放失败，" + song.error);
              }
              modal.offModal();
              clearInterval(interval);
            }
          }, 100);
          break;
        }
        case "history": {
          music.playModal(musicInfoList[index], {isAddHistory: false, type: "history"});
          playbackComplete();
          break;
        }
        case "collection": {
          if (musicInfoList[index].url) {
            music.playModal(musicInfoList[index], {isAddHistory: true, type: "collection"});
            playbackComplete();
          } else {
            if ("NET" === musicInfoList[index].type) {
              modal.onModal();
              store.state.kugouNet.song = {};
              store.dispatch("kugouNet/getSongNetStore", musicInfoList[index].id);
              let song;
              let interval = setInterval(() => {
                song = store.state.kugouNet.song;
                console.log("song", song)
                if (song && (song.url || song.error)) {
                  if (song.url) {
                    playMusic(song, {});
                  } else {
                    musicInfoList[index].isPlay = false;
                    alert.dangerAlert("播放失败，" + song.error);
                  }
                  modal.offModal();
                  clearInterval(interval);
                }
              }, 100);
            }
            // [{"id":"27D327198ED90ADBADACCA958572069F","type":"NET","title":"大约在冬季","artist":"齐秦","album":"","size":"3.56M","isLoading":false,"isPlaying":false,"isCollection":true,"isPlay":true}]
          }
          break;
        }
        default:
          music.playModal(musicInfoList[index], {modalNo: false});
          playbackComplete();
      }
    }

    /**
     * 标题：播放单曲
     *
     * 清空播放列表
     *
     * 变量：song，要播放的音乐<br />
     * 变量：isEmpty，是否先清空当前播放列表<br />
     * 变量：isAddHistory，是否要添加到历史记录<br />
     * 变量：modalNo，是否打开遮罩<br />
     */
    function playMusic(song, {isEmpty = true, isAddHistory = true, modalNo = false}) {
      if (isEmpty) {
        store.commit("ADD_MUSIC_EMPTY", song);
      } else {
        store.commit("ADD_MUSIC", song);
      }
      if (isAddHistory) {
        addHistory(song);
      }
      music.playModal(song, {modalNo});
      playbackComplete();
    }

    /**
     * 标题：播放全部
     *
     * 清空播放列表，并播放第一首
     *
     * 变量：<br />
     */
    function playMusicAll() {
      // 播放选中
      if (operation.value) {
        operation.value = false;
        let musicList = musicInfoList.filter(song => song.isSelected === true);
        if (musicList.length > 0) {
          // 添加到播放列表，并播放第一首
          store.commit("ADD_MUSIC_LIST_EMPTY", musicList);
          batchAcquisitionMusic(musicList)
        } else {
          alert.warningAlert("未选择任何选项！")
        }
      } else { // 播放全部
        store.commit("ADD_MUSIC_LIST_EMPTY", musicInfoList);
        batchAcquisitionMusic(musicInfoList);
      }
    }

    /**
     * 标题：批处理操作开关
     */
    function batchOperation() {
      operation.value = !operation.value;
    }

    /**
     * 标题：批量处理音乐
     *
     * 变量：musicList，要处理的音乐列表<br />
     */
    function batchAcquisitionMusic(musicList, isPlay = true, index = 0) {
      isPlay ? modal.onModal() : "";
      store.state.kugouNet.song = {};
      store.dispatch("kugouNet/getSongNetStore", musicList[index].id);
      let song;
      let time = 100;
      let interval = setInterval(() => {
        time += 100;
        console.log("递归", index)
        song = store.state.kugouNet.song;
        if (time > 2000 || (song && (song.url || song.error))) {
          song.isLoading = false;
          if (song.url) {
            if (isPlay) {
              isPlay = false;
              music.playModal(song, {});
            }
          } else {
            song.isPlay = false;
            //store.state.kugouNet.musicList[index].isPlay = false;
            store.commit("kugouNet/SET_MUSIC_BY_ID", song);
            alert.dangerAlert(song.title + "，出现异常");
          }
          addMark([song]);
          // 修改播放列表
          store.commit("SET_MUSIC_BY_ID", song);
          clearInterval(interval);
          if (index < musicList.length - 1) {
            index++;
            batchAcquisitionMusic(musicList, isPlay, index);
          }
          if (index >= musicList.length - 1 && modal.getStatus() === "on") {
            modal.offModal();
            alert.dangerAlert("全部播放失败");
          }
        }
      }, 100);
    }

    /**
     * 标题：添加到播放列表
     *
     * 不清空播放列表，向当前播列表后追加
     *
     * 变量：<br />
     */
    function addMusic(musicList) {

    }

    let playingId = -1;
    let playbackCompleteClose;
    /**
     * 标题：检测是否播放完成
     *
     * 变量：<br />
     */
    let playbackComplete = function () {
      clearInterval(playbackCompleteClose);
      playbackCompleteClose = setInterval(() => {
        //console.log("运行检测")
        // 获取正在播放歌曲的id
        let id = music.player.id;
        // 播放列表不小于1，且当前播放器记录id与播放列表记录id不一致
        if (musicInfoList.length && playingId !== id) {
          playingId = id;
          musicInfoList.forEach((m) => {
            m.isPlaying = m.id === id;
          })
          //store.commit("SET_MUSIC_PLAYING", id);
        }
      }, 100);
    }

    /**
     * 标题：添加到收藏夹
     *
     * 变量：index，当前播放第几首音乐<br />
     */
    function addHistory(musicInfo, isHistory = true) {
      // 添加到历史记录
      store.commit("history/ADD_MUSIC_HISTORY", musicInfo);
      // 查看
      // store.commit("ADD_MARK", musicInfo);
      // music.setCollection(musicInfo, isCollection);
    }

    /**
     * 标题：添加到收藏夹
     *
     * 变量：index，当前播放第几首音乐<br />
     */
    function addCollection(index, isCollection = true) {
      let musicInfo = musicInfoList[index];
      musicInfo.isCollection = isCollection;
      // 添加收藏
      store.commit("collection/ADD_MUSIC_COLLECTION", musicInfo);
      // 查看
      // store.commit("ADD_MARK", musicInfo);
      // music.setCollection(musicInfo, isCollection);
    }

    /**
     * 标题：全选
     */
    let checkAll = computed({
      get() {
        return musicInfoList.every(item => item.isSelected);
      },
      set(value) {
        return musicInfoList.forEach(item => (item.isSelected = value));
      }
    })

    /**
     * 标题：页面样式
     *
     * 变量：isPlay，是否可以播放<br />
     * 变量：isPlaying，是否正在播放<br />
     */
    const getClass = computed(() => (isPlay, isPlaying) => {
      let c1 = isPlay || isPlay === undefined ? 'play' : 'not-play';
      let c2 = isPlaying || isPlaying === undefined ? 'selected' : 'not-selected';
      return c1 + ' ' + c2;
    })

    onMounted(() => {
      if (music.player.id !== '-1') {
        playbackComplete();
      }
    });

    onBeforeUnmount(() => {
      clearInterval(playbackCompleteClose);
    });
    /*watch(route, (newValue, oldValue) => {
      songSheet.type = route.query.type;
      setPageStyle();
    });*/
    return {
      songSheet,
      musicInfoList,
      additionShow,
      downloadShow,
      deleteShow,
      operation,
      checkAll,

      playMusicAll,
      addMusic,

      addCollection,
      play,
      getClass,
      batchOperation
    }
  },
}
</script>

<style scoped lang="less">
@import url("@/assets/less/1.less");

.music-list {

  width: 1010px - 25px;

  .header {
    height: 200px;
    margin-bottom: 20px;
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    align-content: center;
    justify-content: flex-start;
    align-items: center;

    & > div:first-child {
      width: 200px;
      height: 200px;
      background-size: 200px;
      border-radius: 6px;
    }

    & > div:last-child {
      margin-left: 20px;
      display: flex;
      flex-direction: column;
      flex-wrap: nowrap;
      justify-content: space-evenly;
      align-content: flex-start;
      align-items: flex-start;
      height: 200px;
      color: @fbc;

      & > span:nth-child(1) {
        color: @ffc;
        font-size: 30px;
      }

      & > span:nth-child(2) {
        display: inline-block;
        width: 44rem;
        height: 4rem;
        // 超过部分隐藏
        overflow: hidden;
        // 超过部分用...代替
        text-overflow: ellipsis;
      }

      .tool {
        display: flex;
        flex-direction: row;
        flex-wrap: nowrap;
        align-content: center;
        justify-content: flex-start;
        align-items: center;

        div {
          margin-right: 20px;
          display: flex;
          flex-direction: row;
          flex-wrap: nowrap;
          align-content: center;
          justify-content: center;
          align-items: center;
          width: 110px;
          height: 32px;
          background-color: @fc;
          border-radius: 32px;
          font-size: 14px;
          transition: background-color 0.5s ease 0s;

          span {
            color: @fcc;
          }

          svg {
            padding-right: 5px;
            .icon-min();
          }

          &:hover {
            // background-color: #1ece99;
            background-color: @sc;
            transition: all 0.5s ease 0s;
            cursor: default;
          }
        }

        & > div:nth-child(2) {
          width: 140px;
        }

        & > div:nth-child(5) {
          width: 130px;
        }

        & > div:nth-child(2) svg {
          width: 18px;
          height: 18px;
        }

        & > div:nth-child(3) svg {
          width: 18px;
          height: 18px;
        }

        & > div:nth-child(4) svg {
          width: 14px;
          height: 14px;
        }

        & > div:nth-child(5) svg {
          width: 16px;
          height: 16px;
        }
      }
    }
  }

  .table {
    width: 100%;
    height: 550px;
    /*border: 1px solid #4cb9fc;*/
    overflow-x: hidden; /*x轴禁止滚动*/
    overflow-y: scroll; /*y轴滚动*/

    /* 定义滚动条样式 */

    &::-webkit-scrollbar {
      //display: none;
      width: 10px; //定义滚动条宽度
      height: 10px; //定义滚动条高度
      /*width: 20px;*/
      border-radius: 10px; //定义滚动条圆角
      background-color: rgba(240, 240, 240, 0.1); //定义滚动条颜色
    }

    /*定义滚动条轨道 内阴影+圆角*/

    &::-webkit-scrollbar-track {
      border-radius: 10px;
      /*滚动条里面轨道*/
      background: @bc;
    }

    /*&::-webkit-scrollbar-track {
      display: none;
      box-shadow: inset 0 0 0px rgba(240, 240, 240, .5); //定义轨道阴影
      border-radius: 10px; //定义轨道圆角
      background-color: rgba(4, 56, 114, .5); //定义轨道颜色
    }*/

    /*定义滑块 内阴影+圆角*/

    &::-webkit-scrollbar-thumb {
      border-radius: 10px; //定义滑块圆角
      box-shadow: inset 0 0 0 rgba(240, 240, 240, .5); //定义滑块阴影
      background-color: @fc //定义滑块颜色
    }

    table {
      position: relative;
      width: 100%;
      text-align: left;
      border-collapse: collapse;
      border-spacing: 0;

      th, td {
        padding: 0;
      }

      thead {
        position: sticky;
        top: 0;
        height: 50px;
        background-color: @bc;
        color: @fbc;
        /*border: 1px solid #ea4a36;*/

        tr {
          & > td:nth-child(1) {
            //width: 20px;
            padding-left: 10px;
          }

          & > td:nth-child(2) {
            //padding-left: 20px;
            width: 40%;
          }

          & > td:nth-child(4) {
            width: 30%;
          }

          & > td:nth-child(5) {
            width: 5%;
            max-width: 5%;
          }
        }
      }

      tbody {
        color: @ffc;

        tr {
          height: 50px;
          /*border: 1px solid #ea4a36;*/

          td:nth-child(1) {
            padding-left: 10px;
          }

          td:nth-child(2) {
            /*padding-left: 20px;*/
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            align-items: center;
            align-content: center;
            flex-wrap: nowrap;
            cursor: pointer;
            height: 50px;

            div:first-child {
              display: flex;
              flex-direction: row;
              flex-wrap: nowrap;
              align-content: center;
              justify-content: flex-start;
              align-items: flex-start;
              height: 22px;
              .text(18rem);

              span {
                svg {
                  fill: #f0a732;
                }
              }
            }

            div:last-child {
              display: flex;
              flex-direction: row;
              flex-wrap: nowrap;
              align-content: center;
              justify-content: center;
              align-items: center;
              width: 128px;
              height: 22px;

              span {
                margin-right: 10px;
              }
            }
          }

          td:last-child {
            padding-right: 20px;
          }
        }
      }
    }
  }
}

input[type=checkbox] {
  zoom: 150%;
}

.not-active {
  svg {
    .icon-min(22px, @fbc)
  }

  &:hover {
    svg {
      fill: @fcc;
    }
  }
}

.active {
  svg {
    .icon-min(22px, @sc)
  }
}

.not-play {
  color: @fbc;
  cursor: not-allowed;
  pointer-events: none;
}

.play {
  &:hover {
    .selected;
  }
}

.not-selected {

}

.selected {
  @radius: 5px;
  cursor: default;

  td {
    background-color: #505663;
  }

  td:first-child {
    border-radius: @radius 0 0 @radius;
  }

  td:last-child {
    border-radius: 0 @radius @radius 0;
  }
}

</style>

